package com.spzx.domain;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.spzx.product.api.domain.Category;
import com.spzx.service.CategoryService;
import com.spzx.service.impl.CategoryServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Component
public class CategoryExcelListener extends AnalysisEventListener<Category> {
    @Resource
    CategoryService  categoryService;
    private List<Category> categories = new ArrayList<>();
    private int limit = 100;

    public CategoryExcelListener(CategoryServiceImpl categoryService) {
        this.categoryService = categoryService;
    }

    @Override
    public void invoke(Category category, AnalysisContext analysisContext) {
        Boolean exists = categoryService.exists(category);
        categories.add(category);
        if(exists){return;}
        if(categories.size()>limit){
            boolean saveBatch = categoryService.saveBatch(categories);
            categories.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(categories.size()>0){
            boolean saveBatch = categoryService.saveBatch(categories);
            categories.clear();
        }
    }
}
